package com.sky.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Category;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.SetmealDish;
import com.sky.exception.BaseException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishFlavorService;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import net.bytebuddy.implementation.bytecode.Throw;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.List;

@Service
@RequiredArgsConstructor

public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {
    private final DishFlavorService dishFlavorService;

    @Override
    public PageResult selecetDishPage(DishPageQueryDTO dto) {

        Integer page = dto.getPage();
        Integer pageSize = dto.getPageSize();
        if (ObjectUtil.isNull( page) || ObjectUtil.isNull(pageSize)){
            throw new BaseException(MessageConstant.PAGE_PARAM_NO_NULL);
        }
        Math.max(page, 1);
        Math.max(pageSize, 5);

        Page<Dish> dishPage = new Page<>(page, pageSize);

        // 使用更准确的条件判断
        lambdaQuery()
                .like(ObjectUtil.isNotEmpty(dto.getName()), Dish::getName, dto.getName())
                .eq(dto.getStatus() != null, Dish::getStatus, dto.getStatus())
                .eq(dto.getCategoryId() != null, Dish::getCategoryId, dto.getCategoryId())
                .orderByDesc(Dish::getUpdateTime)
                .page(dishPage);

        List<Dish> dishList = dishPage.getRecords();
        List<DishVO> dishVOList = BeanUtil.copyToList(dishList, DishVO.class);

        // 查询分类信息
        List<Category> categoryList = Db.lambdaQuery(Category.class).list();

        // 健壮性检查：确保分类列表不为空
        if (CollUtil.isEmpty(categoryList)) {
            throw new BaseException("分类信息不存在");
        }

        // 设置分类名称
        dishVOList.forEach(dishVO -> {
            String categoryName = categoryList.stream()
                                              .filter(category -> category.getId().equals(dishVO.getCategoryId()))
                                              .findFirst()
                                              .map(Category::getName)
                                              .orElse(null);
            dishVO.setCategoryName(categoryName);
        });

        // 正确构建并返回分页结果
        return PageResult.builder()
                         .total(dishPage.getTotal())
                         .records(dishVOList)
                         .build();
    }

    @Override
    @Transactional
    public void add(DishDTO dto) {
        Dish dish = BeanUtil.toBean(dto, Dish.class);
        dish.setStatus(1);
        save(dish);
        List<DishFlavor> flavors = dto.getFlavors();
        if (CollUtil.isEmpty(flavors)) {
            return;
        }
        flavors.forEach(dishFlavor -> dishFlavor.setDishId(dish.getId()));
        //批量插入菜品口味 数据
        dishFlavorService.saveBatch(flavors);

    }

    @Override

    @Transactional
    public void updateDish(DishDTO dto) {
        Dish dish = BeanUtil.toBean(dto, Dish.class);
        updateById(dish);
        List<DishFlavor> flavors = dto.getFlavors();
        if (CollUtil.isEmpty(flavors)) {
            return;
        }
        dishFlavorService.remove(Wrappers.<DishFlavor>lambdaQuery()
                                         .eq(dish.getId() != null, DishFlavor::getDishId, dish.getId())
        );
        dishFlavorService.saveBatch(flavors);
    }

    @Override
    public DishVO selectDishById(Long id) {
        Dish dish = getById(id);
        if (dish == null) {
            throw new BaseException(MessageConstant.DISH_NOT_FOUND);
        }
        DishVO dishVO = BeanUtil.toBean(dish, DishVO.class);
        dishVO.setFlavors(dishFlavorService.list(Wrappers.<DishFlavor>lambdaQuery()
                                                         .eq(DishFlavor::getDishId, id)));
        return dishVO;
    }

    @Override
    public List<DishVO> selectByCategoryId(Long categoryId) {
        List<Dish> list = lambdaQuery().eq(Dish::getCategoryId, categoryId)
                                       .eq(Dish::getStatus, 1)
                                       .orderByDesc(Dish::getUpdateTime).list();
        if (CollUtil.isEmpty(list)) {
            return List.of();

        }

        return BeanUtil.copyToList(list, DishVO.class);
    }

    @Override
    @Transactional
    public void removeDishByIds(List<Long> ids) {
        if (CollUtil.isEmpty(ids)){
            throw new BaseException("请选择要删除的菜品");
        }
        //若菜品关联着套餐，则不能删除
        List<SetmealDish> list = Db.lambdaQuery(SetmealDish.class).in(SetmealDish::getDishId, ids).list();
        if (CollUtil.isNotEmpty(list)){
            throw new BaseException(MessageConstant.CATEGORY_BE_RELATED_BY_DISH);
        }
        removeByIds(ids);
        dishFlavorService.remove(Wrappers.<DishFlavor>lambdaQuery()
                                         .in(DishFlavor::getDishId, ids));
    }


}

